package com.hjw.weixun.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hjw.weixun.Template.JdbcTemplate;
import com.hjw.weixun.dao.FollowerDao;
import com.hjw.weixun.db.JdbcUtil;
import com.hjw.weixun.domain.Follower;
import com.hjw.weixun.domain.User;
import com.hjw.weixun.domain.Weixun;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;

public class FollowerDaoJdbcImpl extends JdbcTemplate<Follower> implements
		FollowerDao {

	public static FollowerDao followerDao;

	public static FollowerDao getInstance() {
		if (followerDao == null) {
			followerDao = new FollowerDaoJdbcImpl();
		}
		return followerDao;
	}

	@Override
	public List<Integer> getPubishers(Integer followerId) {
		String sql = "select userid from follower where id =? ";
		Object[] args = new Object[] { followerId };
		// List<Integer> userIds=getSingleColum(sql,followerId);
		return null;
	}

	@Override
	public List<Follower> getFollowers(Integer weixunId) {
		List<Follower> followers = null;
		String sql = "select *  from follower where weixunid =? ";
		Object[] args = new Object[] { weixunId };
		Connection conn = JdbcUtil.getInstance().getConnection();
		PreparedStatement pstat = null;
		ResultSet rs = null;
		try {
			pstat = (PreparedStatement) conn.prepareStatement(sql);
			for (int i = 1; i <= args.length; i++) {
				pstat.setObject(i, args[i - 1]);
			}
			rs = pstat.executeQuery();
			try {

				followers = this.populate(rs, Follower.class);
				for (int i = 0; i < followers.size(); i++) {
					Follower follower = (Follower) followers.get(i);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} finally {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.free(null, pstat, conn);
		}
		return followers;
	}

	@Override
	public boolean isFollower(Weixun weixun, User user) {

		String sql = "SELECT * FROM follower WHERE weixunid = ? and followerid = ?";

		Object[] args = new Object[] { weixun.getId(), user.getUserid() };

		return null == this.uniqueResult(sql, args) ? false : true;
	}

	@Override
	public void addFollower(Weixun weixun, User user) {
		String sql = "INSERT INTO follower(weixunid,followerid) VALUES (?,?)";
		
		Object[] args = new Object[] { weixun.getId(), user.getUserid() };
		
		this.execute(sql, args);

	}

}
